package com.bang.sgg.service;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.UUID;

/**
 * @Auther: Bang
 * @Date: 2019/11/23 12:02
 * @Description:
 */
@Component
public class MessageServiceImpl<T> implements MessageService<T>, RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this::confirm);
        rabbitTemplate.setReturnCallback(this::returnedMessage);
    }

    @Override
    public void send(String exchange, String routingKey, T object, CorrelationData correationData) {
        rabbitTemplate.convertAndSend(exchange, routingKey, object, correationData);
    }

    @Override
    public void send(String exchange, String routingKey, T object) {
        rabbitTemplate.convertAndSend(exchange, routingKey, object,new CorrelationData(UUID.randomUUID().toString()));
    }

    //回调函数: confirm确认
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        System.err.println("correlationData: " + correlationData);
        System.err.println("ack: " + ack);
        if(!ack){
            System.err.println("异常处理...."+cause);
        }
    }

    //回调函数: return返回
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        System.err.println("====================================");
        System.err.println("return exchange: " + exchange + ", routingKey: "
                + routingKey + ", replyCode: " + replyCode + ", replyText: " + replyText);
    }
}
